import gradeGet from "./gradeGet";
import examGet from "./examGet";
import courseGet from "./courseGet";

async function dealWithUserInfo(res, uid, password) {
  console.log(res);
  //用户信息
  var userInfo = res.data.attach;
  userInfo.token = res.data.token;
  userInfo.current_term_code = res.data.current_term_code;
  //处理开学日期
  userInfo.first_day = new Date(res.data.first_day);
  var year = parseInt(uid.substring(0, 4)); //入学年份
  var last = year - 1;
  var next1 = year + 1;
  var next2 = year + 2;
  var next3 = year + 3;
  var next4 = year + 4;
  var next5 = year + 5;
  var next6 = year + 6;
  var terms = [
    last + "-" + year + "-2",
    year + "-" + next1 + "-1",
    year + "-" + next1 + "-2",
    next1 + "-" + next2 + "-1",
    next1 + "-" + next2 + "-2",
    next2 + "-" + next3 + "-1",
    next2 + "-" + next3 + "-2",
    next3 + "-" + next4 + "-1",
    next3 + "-" + next4 + "-2",
    next4 + "-" + next5 + "-1",
    next4 + "-" + next5 + "-2",
    next5 + "-" + next6 + "-1",
  ];
  //12个学期
  userInfo.terms = terms;
  userInfo.term = 0;
  //当前学期获取
  for (var i = 0; i < terms.length; i++) {
    if (userInfo.current_term_code == terms[i]) {
      userInfo.term = i;
      // console.log("term : " + i);
      break;
    }
  }
  userInfo.year = year;
  userInfo.online = true;
  //保存学号密码
  userInfo.number = uid;
  userInfo.password = password;
  try {
    await getApp().xutils.setStorage("userInfo", userInfo);
    getApp().globalData.userInfo = userInfo;
  } catch (error) {
    console.log(error);
  }
  return userInfo;
}

async function signup(uid, password, vcode_id) {
  //确保已经获取vcode_id
  if (!vcode_id) {
    vcode_id = await getApp().xutils.getVcodeId();
  }
  var res = await getApp().xutils.request("signup", {
    uid,
    password,
    vcode_id,
  });
  dealWithUserInfo(res, uid, password);
}

async function login(uid, password, vcode_id) {
  var res = await getApp().xutils.request("login", {
    uid,
    password,
    vcode_id,
  });
  await dealWithUserInfo(res, uid, password);
}

function getAll() {
  return Promise.all([
    courseGet.getCourseList(),
    gradeGet.getGradeList(),
    examGet.exam_get(),
  ]);
}

module.exports = {
  signup,
  login,
  getAll,
  dealWithUserInfo,
};
